
package com.shop.cloud.mall.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.core.util.SensitiveUtils;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.mall.common.entity.ConfigLogistics;
import com.shop.cloud.mall.admin.service.ConfigLogisticsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;


/**
 * 物流账号配置
 *
 * @author 
 * @date 2023-04-12 11:30:55
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/configlogistics")
@Tag(description = "configlogistics", name = "物流账号配置管理")
public class ConfigLogisticsController {

    private final ConfigLogisticsService configLogisticsService;

    /**
     * 物流账号配置查询
     * @return R
     */
    @Operation(summary = "物流账号配置查询")
    @GetMapping
    @PreAuthorize("@ato.hasAuthority('mall:configlogistics:get')")
    public R get() {
		ConfigLogistics configLogistics = configLogisticsService.getOne(Wrappers.emptyWrapper());
		//数据脱敏
		if(configLogistics != null){
			String sensitiveLogisticsKey = SensitiveUtils.process(configLogistics.getLogisticsKey());
			configLogistics.setLogisticsKey(sensitiveLogisticsKey);
		}

        return R.ok(configLogistics);
    }

    /**
     * 物流账号配置修改
     * @param configLogistics 物流账号配置
     * @return R
     */
    @Operation(summary = "物流账号配置修改")
    @SysLog("修改物流账号配置")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('mall:configlogistics:edit')")
    public R updateById(@RequestBody ConfigLogistics configLogistics) {
		if(StrUtil.isNotBlank(configLogistics.getId())){
			//数据脱敏
			ConfigLogistics configLogisticsOld = configLogisticsService.getById(configLogistics.getId());
			String logisticsKey = configLogisticsOld.getLogisticsKey();
			if(StrUtil.isNotBlank(logisticsKey)){
				String sensitiveLogisticsKey = SensitiveUtils.process(logisticsKey);
				if(!sensitiveLogisticsKey.equals(configLogistics.getLogisticsKey())){
					logisticsKey = configLogistics.getLogisticsKey();
				}
				configLogistics.setLogisticsKey(logisticsKey);

			}

			configLogisticsService.updateById(configLogistics);
			return R.ok(configLogistics);
		}else{
			configLogisticsService.save(configLogistics);
			return R.ok(configLogistics);
		}
    }

	/**
	 * 获取物流公司信息
	 * @return R
	 */
	@Operation(summary = "获取物流公司信息")
	@GetMapping("/logisticscompany")
	public R getLogisticsCompany() {
		ConfigLogistics configLogistics = configLogisticsService.getOne();
		if(configLogistics == null){
			return R.ok(null);
		}
		return R.ok(configLogistics.getLogisticsCompany());
	}
}
